var Mongoose = require('mongoose'),
    util = require('../helpers/util');


var abuseSchema = Mongoose.Schema({
    user: {
        type: Mongoose.Schema.ObjectId,
        required: true,
        ref: 'User'
    },
    idea: {
        type: Mongoose.Schema.ObjectId,
        required: true,
        ref: 'Idea'
    },
    category: {
        type: String,
        default: ''
    },
    reason: {
        type: String,
        default: ''
    },
    status: {
        type: String,
        default: "Rejected"
    }
}, {timestamps: true});

var Abuse = Mongoose.model('Abuse', abuseSchema);

Abuse.createNewAbuse = function (newAbuse, callback) {
    newAbuse.save(callback);
};

Abuse.getIdeaAbuseCount = function (ideaID, callback) {
    Abuse.find({idea: new Mongoose.Types.ObjectId(ideaID)}).count(callback);
};

Abuse.getAllAbuses = function (userId, params, callback) {

    var getTitle, getUser, getCategory, getReason;
    if (params.searchParameter === 'Title') {
        getTitle = params.searchValue;
    } else if (params.searchParameter === 'User') {
        getUser = params.searchValue;
    } else if (params.searchParameter === 'Category') {
        getCategory = params.searchValue;
    } else if (params.searchParameter == 'Reason') {
        getReason = params.searchValue;
    }

    var skipItem = params.skipItem || 0,
        itemsperPage = params.itemsperPage || 6,
        sortParameter = params.sortParameter || 'createdAt',
        sortOrder = ((params.sortOrder === 'ascending') ? 1 : -1),
        sort = {},
        skip = parseInt(skipItem),
        limit = parseInt(itemsperPage),
        inputFromDate = params.fromDate,
        toDate = params.toDate;
    sort[sortParameter] = sortOrder;

    var searchTitle = new RegExp('^' + getTitle, "i"),
        searchUser = new RegExp('^' + getUser, "i"),
        searchCategory = new RegExp('^' + getCategory, "i"),
        searchReason = new RegExp('^' + getReason, "i");


    var searchMatchSecondary = {};
    if (getTitle) {
        searchMatchSecondary = {title: searchTitle};
    } else if (getUser) {
        searchMatchSecondary = {name: searchUser};
    } else if (getCategory) {
        searchMatchSecondary = {category: searchCategory};
    } else if (getReason) {
        searchMatchSecondary = {reason: searchReason};
    } else {
        searchMatchSecondary = {};
    }

    var fromDate = util.getDateWithoutTimeStamp(inputFromDate);
    var todate1 = util.getDateWithoutTimeStamp(toDate);
    var endDate = new Date(todate1.getTime() + (24 * 60 * 60 * 1000));
    var searchMatch = {$and: [{createdAt: {$gte: fromDate, $lt: endDate}}, {status: "Rejected"}]};

    Abuse.aggregate([
        {$match: searchMatch},
        {"$sort": sort},
        {"$skip": skip},
        {"$limit": limit},
        {
            $project: {
                "_id": "$_id",
                "createdAt": "$createdAt",
                "user": "$user",
                "category": "$category",
                "reason": "$reason",
                "idea": "$idea",
                "status": "$status"
            }
        },
        {
            $lookup: {
                "from": "users",
                "localField": "user",
                "foreignField": "_id",
                "as": "users"
            }
        },
        {
            $unwind: "$users"
        },
        {
            $project: {
                "_id": "$_id",
                "createdAt": "$createdAt",
                "user": "$user",
                "category": "$category",
                "reason": "$reason",
                "idea": "$idea",
                "name": {$concat: ["$users.firstName", " ", {$ifNull: ["$users.lastName", " "]}]},
                "status": "$status"
            }
        },
        {
            $lookup: {
                "from": "ideas",
                "localField": "idea",
                "foreignField": "_id",
                "as": "ideas"
            }
        },
        {
            $unwind: "$ideas"
        },
        {
            $project: {
                "_id": "$_id",
                "createdAt": "$createdAt",
                "user": "$user",
                "category": "$category",
                "reason": "$reason",
                "idea": "$idea",
                "name": "$name",
                "title": "$ideas.title",
                "status": "$status",
                "spam": "$ideas.spam"
            }
        },
        {$match: searchMatchSecondary},
        {
            $project: {
                "_id": "$_id",
                "createdAt": "$createdAt",
                "user": "$user",
                "category": "$category",
                "reason": "$reason",
                "idea": "$idea",
                "name": "$name",
                "title": "$title",
                "status": "$status",
                "spam": "$spam"

            }
        }
    ], callback);
};

Abuse.getAbuseById = function (id, callback) {
    Abuse.findById(id, callback);
};

Abuse.deleteAbuseByIdea = function (ideaId, callback) {
    Abuse.find(
        {'idea': Mongoose.Types.ObjectId(ideaId)}
    ).remove(callback);
};
module.exports = Abuse;